import re
from scholarly import scholarly
# https://scholarly.readthedocs.io/en/stable/quickstart.html
def extract_paper_titles(text):
    # 使用正则表达式匹配 [num] 格式的开头，并提取后面的标题
    pattern = r'\[\d+\]\s*(.*)'
    matches = re.findall(pattern, text)
    return matches

def fetch_bibtex(titles):
    bibtex_entries = []
    for title in titles:
        search_query = scholarly.search_pubs(title)  # 使用scholarly库搜索论文并且获得一个可迭代对象
        # search_query = scholarly.search_keyword(title)
        print(search_query)
        try:
            pub = next(search_query).fill()  # 获取详细信息
            bibtex = pub.bib
            bibtex_str = f"@{bibtex['entry_type']}{{{bibtex['ID']},\n"
            for key, value in bibtex.items():
                if key != 'ID' and key != 'entry_type':
                    bibtex_str += f"  {key} = {{{value}}},\n"
            bibtex_str = bibtex_str.rstrip(',\n') + "\n}"
            bibtex_entries.append(bibtex_str)
        except StopIteration:
            print(f"No results found for '{title}'")
            bibtex_entries.append(f"% No BibTeX entry found for: {title}")
    return bibtex_entries

def extract_paper_titles(text):
    # 使用正则表达式匹配 [num] 格式的开头，并提取后面的标题
    pattern = r'\[\d+\]\s*(.*)'
    matches = re.findall(pattern, text)
    return matches

def fetch_gb7714_entries(titles):
    gb7714_entries = []
    for title in titles:
        search_query = scholarly.search_pubs(title)  # 使用scholarly库搜索论文并且获得一个可迭代对象
        # print(search_query)
        try:
            pub = next(search_query)
            print(pub)
            authors = ', '.join([author for author in pub['bib']['author']])
            year = pub['bib']['year'] if 'year' in pub['bib'] else ''
            print(f'authors: {authors},year: {year}')
            venue = pub['bib'].get('booktitle', '') or pub['bib'].get('journal', '')
            volume = pub['bib']['volume'] if 'volume' in pub['bib'] else ''
            number = pub['bib']['number'] if 'number' in pub['bib'] else ''
            pages = pub['bib']['pages'] if 'pages' in pub['bib'] else ''
            #  = pub.number if hasattr(pub, 'number') else ''
            #  = pub.pages if hasattr(pub, 'pages') else ''
            
            # 构建GB/T 7714格式的参考文献条目
            gb7714_entry = f"{authors}. ({year}). {pub['bib']['title']}. In: {venue}"
            if volume:
                gb7714_entry += f". Vol. {volume}"
            if number:
                gb7714_entry += f", No. {number}"
            if pages:
                gb7714_entry += f", pp. {pages}"
            gb7714_entries.append(gb7714_entry)
        except StopIteration:
            print(f"No results found for '{title}'")
            gb7714_entries.append(f"% No GB/T 7714 entry found for: {title}")
    return gb7714_entries

if __name__ == "__main__":
    # 示例文本
    text = """[19]Improving vision-and-language navigation with imagetext pairs from the web.
[20]Towards learning a generic agent for vision-and-language navigation via pretraining.
[21]Vln bert: A recurrent vision-and-language bert for navigation. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)"""

    # 提取论文标题
    paper_titles = extract_paper_titles(text)
    # print(dir(scholarly))
    # 获取BibTeX信息
    bibtex_list = fetch_gb7714_entries(paper_titles)

    # 打印BibTeX条目
    for bib_entry in bibtex_list:
        print(bib_entry)